package com.cloudea.learn.metric;

import com.cloudea.learn.Tensor;
import com.cloudea.learn.layer.ElementAvg;
import com.cloudea.learn.layer.ElementPow2;
import com.cloudea.learn.layer.ElementSub;

import java.util.List;

/**
 * 均方误差
 * loss = (1 / n) \sum_i (y_i - y_hat_i)^2
 * @author cloudea
 * @date 2021/12/29
 */
public class MeanSquareError implements Metric {
    @Override
    public Tensor measure(List<Tensor> groundTruth, List<Tensor> output) {
        Tensor[] distances = new Tensor[output.size()];
        for (int i = 0; i < groundTruth.size(); i++){
            Tensor truth = groundTruth.get(i);
            Tensor pred = output.get(i);
            Tensor distance = new ElementSub().call(truth, pred);
            Tensor distance2 = new ElementPow2().call(distance);
            distances[i] = distance2;
        }
        return new ElementAvg().call(distances);
    }
}
